const config = require('../../config/index')
const { wxRequest } = require('../../utils/util')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseUrl: config.baseUrl,
    loanTermRange:[
        {
          id:'000300',
          name:'3个月'
        },
        {
          id:'000600',
          name:'6个月'
        },
        {
          id:'000900',
          name:'9个月'
        },
        {
          id:'010000',
          name:'12个月'
        },
    ],
    // 归属行下拉
    loanBelongs: [],
    agreementChecked: false,
    countdown: 0,
    type: wx.getStorageSync('InvoiceLoanProductType'),
    formData: {
      // 统一社会信用代码
      licenseCode: '',
      // 法定代表人姓名
      custName: '',
      // 法定代表人证件号码
      certCode: '',
      // 企业名称
      busiName: '',
      // 企业征信授权书地址
      creditPath: [],
      // 企业营业执照
      businessLicensePath: [],
      // 客户姓名
      applyName:'',
      // 申请金额
      appAmt:'',
      // 贷款期限
      crdTerm: {},
      // 授信期限
      crdNstdTerm: '',
      // 核心企业
      coreEnterprise: {},
      // 贷款归属行
      landbank: {},
      // 推荐人柜员号
      referee: '',
      // 客户经理编号
      acctUsercode: '',
      // 居住地址
      liveAddr: {},
      // 详细地址
      detailAddr: '',
      // 验证码
      captcha:'',
      // 产品代码
      prdCode: wx.getStorageSync('InvoiceLoanPrdCode'),
      // 贷款用途
      loanPurpose: '生产经营'
    },
    dynamicRules: [
      {
        name:'licenseCode',
        rules: [
          {required:true, message:'请输入统一社会信用代码'},
          {validator(rule,val){
            if(val.length!==18) {
              return '统一社会信用代码格式错误'
            }
          }}
        ]
      },
      {
        name:'custName',
        rules: [{required:true, message:'请输入法定代表人姓名'}]
      },
      {
        name:'certCode',
        rules: [
          { required:true, message:'请输入法定代表人身份证号' },
        ]
      },
      {
        name:'busiName',
        rules: [{required:true, message:'请输入企业名称'}]
      },
      {
        name:'creditPath',
        rules: [
          {required:true, message:'请上传企业征信授权书'},
          {validator(rule,val){
            if(!val.length) {
              return '请上传企业征信授权书'
            }
          }}
        ]
      },
      {
        name:'businessLicensePath',
        rules: [
          {required:true, message:'请上传企业营业执照'},
          {validator(rule,val){
            if(!val.length) {
              return '请上传企业营业执照'
            }
          }}
        ]
      },
      {
        name:'applyName',
        rules: [{required:true, message:'请输入您的姓名'}]
      },
      {
        name:'crdTerm',
        rules: [
          {required:true, message:'请选择贷款期限'},
          {validator(rule,val){
            if(!val?.info) {
              return '请选择贷款期限'
            }
          }}
        ]
      },
      {
        name:'landbank',
        rules: [
          {required:true, message:'请选择贷款归属行'},
          {validator(rule,val){
            if(!val?.info) {
              return '请选择贷款归属行'
            }
          }}
        ]
      },
      {
        name:'liveAddr',
        rules: [
          {required:true, message:'请选择居住地址'},
          {validator(rule,val){
            if(!val?.info) {
              return '请选择居住地址'
            }
          }}
        ]
      },
      {
        name:'detailAddr',
        rules: [{required:true, message:'请输入详细地址'}]
      },
      {
        name:'captcha',
        rules: [{required:true, message:'请输入验证码'}]
      },
    ],
    timer:null,
    formDataTimer: null,
    show:false,
    tabKey: 'creditLetter',
    creditPath:'',
    businessLicensePath: '',
    liveAddr: '',
    projectId: '',
    accountUserId: wx.getStorageSync('InvoiceLoanAccountUserId') || '',
    theme: wx.getStorageSync('InvoiceLoanTheme') || ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const amtStr = wx.getStorageSync('InvoiceLoanAmt')
    const customerInfoStr = wx.getStorageSync('InvoiceLoanCustomerInfo')
    const formDataStr = wx.getStorageSync('InvoiceLoanFormData') 
    const type = wx.getStorageSync('InvoiceLoanProductType')
    const customerInfo = JSON.parse(customerInfoStr || '{}')
    const amt = JSON.parse(amtStr || '{}')
    const that = this
    let obj = {
      formData: {},
      businessLicensePath: '',
      creditPath: '',
      liveAddr: ''
    }
    if(formDataStr) {
      obj = JSON.parse(formDataStr)
    }
    this.setData({
      type,
      dynamicRules: [...that.data.dynamicRules, 
        {
          name: 'appAmt',
          rules: [
            {required:true, message:'请输入申请金额'},
            {min: amt.min, message:`金额不能小于${amt.min}`},
            {max: amt.max, message:`金额不能大于${amt.max}`},
            {validator(rule, value){
              const num = Number(value);
              if (isNaN(num)) {
                return "请输入有效数字";
              }
              // 检查是否为整数（避免小数）
              if (!Number.isInteger(num)) {
                return "金额必须是10000的整数";
              }
              
              // 检查是否为10000的倍数
              if (num % 10000 !== 0) {
                return "金额必须是10000的倍数";
              }
            }},
          ]
        },
        {
        name: 'acctUsercode',
        rules: [
          {required: type === 'COMPANY', message:'请输入客户经理编号'}
        ]
        },
      ],
      formData: {
        ...that.data.formData,
        ...obj.formData,
        custName: customerInfo.userName || '',
        applyName: customerInfo.userName || '',
        certCode: customerInfo.idCardNo || '',
      },
      businessLicensePath: obj.businessLicensePath,
      creditPath: obj.creditPath,
      liveAddr: obj.liveAddr,
      accountUserId: wx.getStorageSync('InvoiceLoanAccountUserId') || '',
      theme: wx.getStorageSync('InvoiceLoanTheme') || ''
    })
  },
  onReady(){
    const that = this
    const timer = setInterval(() => {
      const data = {
        formData: {
          ...that.data.formData,
          captcha: ''
        },
        businessLicensePath: that.data.businessLicensePath,
        creditPath: that.data.creditPath,
        liveAddr: that.data.liveAddr
      }
      wx.setStorage({
        key:'InvoiceLoanFormData',
        data: JSON.stringify(data)
      })
    }, 5000)
    that.setData({
      formDataTimer: timer
    })
  },
  onUnload(){
    if(this.data.timer){
      clearInterval(this.data.timer)
    }
    if(this.data.formDataTimer){
      clearInterval(this.data.formDataTimer)
    }
  },
  // 获取贷款归属行
  async queryLoanBelongs(){
    const that = this
    wxRequest({
      url: `${config.baseUrl}/belong/bank/list`,
      invalidCb(){
        that.queryCoreEnterprise()
      },
      success(res){
        that.setData({
          loanBelongs: res.data.data?.map(item=>({
            id: item.instcode,
            name: item.brcname
          }))
        })
      }
    })
  },
  // 查询核心企业
  async queryCoreEnterprise(){
    const that = this
    const { busiName,licenseCode } = that.data.formData
    wxRequest({
      url: `${config.baseUrl}/core/company`,
      method: 'POST',
      data: {
        busiName,
        licenseCode
      },
      invalidCb(){
        that.queryCoreEnterprise()
      },
      success(res){
        that.setData({
          formData: {
           ...that.data.formData,
           coreEnterprise: res.data.data
          }
        })
      }
    })
  },
  // 开户
  async openAccount(){
    const that = this
    return new Promise((resolve,reject)=>{
      const { certCode,custName,licenseCode,busiName, } = that.data.formData
      const invoiceLoanPhone = wx.getStorageSync('InvoiceLoanPhone')
      const productType = wx.getStorageSync('InvoiceLoanProductType')
      wxRequest({
        url: `${config.baseUrl}/apply/open/account`,
        method: 'POST',
        data: {
          appGlobalId: certCode,
          appName: custName,
          clientName: custName,
          entpGlobalId:  licenseCode,
          entpNm: busiName,
          entpTelNo: invoiceLoanPhone,
          globalId: certCode,
          mobileNo: invoiceLoanPhone,
          productType
        },
        fail(){
          reject(new Error(false))
        },
        success(res){
          wx.setStorage({
            key: 'InvoiceLoanAccountUserId',
            data: res.data.data
          })
          that.setData({
            accountUserId: res.data.data, 
          })
          resolve(res.data.data)
        }
      })
    })
  },
  // 签合同
  async signContract(id){
    const that = this
    return new Promise((resolve,reject)=>{
      const productType = wx.getStorageSync('InvoiceLoanProductType')
      wxRequest({
        url: `${config.baseUrl}/captcha/send/contract`,
        method:'POST',
        data: {
          accountUserId: id,
          productType
        },
        invalidCb(){
          that.signContract(id)
        },
        fail(){
          reject(new Error(false))
        },
        success(res){
          that.setData({ countdown: 60 });
          // 设置倒计时定时器
          const timer = setInterval(() => {
            if (that.data.countdown <= 1) {
              clearInterval(timer);
              that.setData({ countdown: 0 });
            } else {
              that.setData({ countdown: that.data.countdown - 1 });
            }
          }, 1000);
          that.setData({
            timer,
            projectId: res.data.data
          })
          resolve(true)
        },
      })
    })
  },
  async fetchVerificationCode() {
    let id = this.data.accountUserId
    if(!id) {
      id = await this.openAccount()
    }
    this.signContract(id)
  },
  handleVerificationCode(){
    const { businessLicensePath,licenseCode,busiName } = this.data.formData
    if(this.data.countdown !== 0) {
      return
    }
    if(!licenseCode) {
      wx.showToast({
        title: '请先填写统一社会信用代码',
        icon: 'none'
      })
      return
    }
    if(licenseCode.length!==18) {
      wx.showToast({
        title: '统一社会信用代码格式错误',
        icon: 'none'
      })
      return
    }
    if(!busiName) {
      wx.showToast({
        title: '请先填写企业名称',
        icon: 'none'
      })
      return
    }
    if(!businessLicensePath.length) {
      wx.showToast({
        title: '请先上传企业营业执照',
        icon:'none'
      })
      return
    }
    this.fetchVerificationCode()
  },
  handleBlurOpenAccount(){
    const { licenseCode,busiName } = this.data.formData
    if(licenseCode && busiName) {
      this.openAccount()
      this.queryCoreEnterprise()
    }
  },
  handleClose(){
    this.setData({
      show: false
    })
  },
  handleRead(){
    this.setData({
      show:false,
      agreementChecked: true,
    })
  },
  handleTab(e){
    const { type } = e.currentTarget.dataset
    this.setData({
      tabKey: type
    })
  },
  handlePreview(e){
    const { type } = e.currentTarget.dataset
    this.setData({
      show:true,
      tabKey: type
    })
  },
  async fetchMangeBlank(cusManager,isSet){
    const { referee,landbank } = this.data.formData
    if(!cusManager) return Promise.resolve(true)
    if(!landbank.info) return Promise.resolve(true)
    const that = this
    const productType = wx.getStorageSync('InvoiceLoanProductType')
    return new Promise((resolve)=>{
      wxRequest({
        url: `${config.baseUrl}/belong/bank/customer/manager/bank`,
        method:'POST',
        data: {
          cusManager,
          loanOpenBrc:landbank.info.id,
          productType,
          referee
        },
        invalidCb(){
          that.fetchMangeBlank(cusManager,isSet)
        },
        success(res){
          if(res.data.code === 200){
            const info = res.data.data
            if(!info) {
              wx.showToast({
                title: res.data.message,
                icon: 'none'
              })
            } else if(isSet){
              that.setData({
                formData: {
                  ...that.data.formData,
                  landbank: {
                    info: {
                      id: info.instcode,
                      name: info.brcname
                    }
                  }
                }
              })
            }
            resolve(true)
          }
        },
        fail(){
          resolve(false)
        }
      }) 
    }) 
  },
  handleCodeInputBlur(e){
    const codeValue = e.detail.value
     this.fetchMangeBlank(codeValue,true)
  },
  fetchSubmit(payload){
    const that = this
    wxRequest({
      url: `${config.baseUrl}/apply/submit`,
      method:'POST',
      data: {
        ...payload
      },
      invalidCb(){
        that.fetchSubmit(payload)
      },
      success(res){
        wx.setStorage({
          key: 'InvoiceLoanFormData',
          data: JSON.stringify({
            businessLicensePath:'',
            creditPath:'',
            formData: {},
            liveAddr: []
          })
        })
        console.log('aaaaaaaaaaaaaaaa',res.data.data);
        wx.navigateTo({
          url: `/pages/success/index?url=${encodeURIComponent(res.data.data)}`,
        })
      }
    })
  },
  handleAgreeChange(e){
    this.setData({
      agreementChecked: e.detail.value.length>0
    })
  },
  handleSubmit(){
    const that = this
    this.selectComponent('#detailForm').validate(async(valid, errors) => {
      const { acctUsercode, crdTerm,businessLicensePath,creditPath,landbank,liveAddr,coreEnterprise,...remain } = this.data.formData
      console.log('crdTerm',crdTerm);
      console.log('landbank',landbank);
      console.log('liveAddr',liveAddr);
      if(valid) { 
        if(!that.data.agreementChecked) {
          wx.showToast({
            title: '请先阅读并同意协议',
            icon: 'none'
          })
          return
        }
        // 发送网络请求        
        const manageBlankPromise = await this.fetchMangeBlank(acctUsercode,false)
        if(!manageBlankPromise) return
        that.fetchSubmit({
          acctUsercode,
          ...remain,
          coreEnterprise:coreEnterprise?.custIdCore || '',
          crdTerm: crdTerm.info.id,
          landbank:landbank.info.id,
          liveAddr: '新疆维吾尔族自治区-'+liveAddr.info.map(item=>item.label).join('-'),
          creditPath: that.data.creditPath,
          businessLicensePath: that.data.businessLicensePath,
          liveAddrCity: liveAddr.info[1].value,
          liveAddrArea: liveAddr.info[0].value,
          phone: wx.getStorageSync('InvoiceLoanPhone'),
          projectId: that.data.projectId,
          authLocation: '乌鲁木齐',
          accountUserId: that.data.accountUserId,
          productType: wx.getStorageSync('InvoiceLoanProductType'),
        })
      } else {
          const firstError = Object.keys(errors)
          if(firstError.length) {
              wx.showToast({
                  title: errors[firstError[0]].message,
                  icon: 'none'
              })
          }
      }
    })
  },
  // 简易双向数据绑定
  handInputChange (e) {
    this.setData({
      [`formData.${e.target.id}`]: e.detail.value
    })
  },
  bindPickerChange(e){
    const { type } = e.currentTarget.dataset
    this.setData({
      formData: {
        ...this.data.formData,
        [type]: {
          info: e.detail.info,
          value: e.detail.value   
        },
      }
    })
  },
  bindPickerRegionChange(e){
    console.log('value',e.detail);
    const { info,value } = e.detail
    this.setData({
      formData: {
        ...this.data.formData,
        liveAddr: {
          info,
          value
        }
      },
      liveAddr: info.map(item=>item.label)
    })
  },
  // 从 Content-Disposition 提取并解码文件名
  extractFilename(contentDisposition) {
    // 情况1：匹配标准格式 filename="encoded_name"
    let match = contentDisposition.match(/filename="([^"]+)"/);
    if (!match) {
      // 情况2：匹配无引号格式 filename=encoded_name
      match = contentDisposition.match(/filename=([^;]+)/);
    }
    
    if (match && match[1]) {
      try {
        // 关键步骤：URL 解码（处理 %E7 这类编码）
        return decodeURIComponent(match[1]);
      } catch (e) {
        console.error('文件名解码失败', e);
      }
    }
    
    // 匹配失败时使用默认文件名
    return 'download_file_' + Date.now() + '.pdf'
  },
  handleDownloadAuthLetter(){
    const documentType = 'USER_USER_CREDIT_AUTH_DOC'
    const token = wx.getStorageSync('InvoiceLoanToken')
    const that = this
    wx.downloadFile({
      url: `${config.baseUrl}/file/download/document/${documentType}`,
      header: {
        Authorization: token
      },
      success(res){
        if (res.statusCode === 200) {
          const contentDisposition = res.header['Content-Disposition'] || '';
          const fileName = that.extractFilename(contentDisposition)
          const fs = wx.getFileSystemManager();
          const savePath = `${wx.env.USER_DATA_PATH}/${fileName}`;
          fs.saveFile({
            tempFilePath: res.tempFilePath,
            filePath: savePath,
            success: (saveRes) => {
              wx.openDocument({
                filePath: saveRes.savedFilePath,
              })
            }
          })
        }
      }
    })
  },
  handleDelete(e){
    this.setData({
      formData: {
        ...this.data.formData,
        [e.currentTarget.dataset.type]: []
      }
    })
  },
  handleFileSelect(e){
    const { type } = e.currentTarget.dataset
    const token = wx.getStorageSync('InvoiceLoanToken')
    const that = this
    wx.uploadFile({
      filePath: e.detail.tempFilePaths[0],
      url: `${config.baseUrl}/file/upload`,
      name:'file',
      header:{
        'Content-Type': 'multipart/form-data',
        Authorization: token
      },
      success(fileE){
        const aaaa = JSON.parse(fileE.data)
        that.setData({
          formData: {
            ...that.data.formData,
            [type]: [
              {
                url:`${config.baseUrl}/file/preview?previewPath=${aaaa.data.previewPath}`,
                loading: false
              }
            ]
          },
          [type]:aaaa.data.ftpPath
        })
      },
      fail(err){
        wx.showToast({
          title: '文件上传失败',
          icon: 'error'
        })
      }
    })
  },
})